// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
let webs = [
    { name: "/ssstwitter.com" },
    { name: "/twittervideodownloader.com" },
    { name: "/poe.com" },
    { name: "/twittervid.com" }
];
chrome.runtime.onInstalled.addListener(() => {
    // fetch("https://www.step2step.cn/mg/script").then(res => { return res.json() }).then(res => {
    //     console.log(res);
    //     webs = res.data;
    // })

});

chrome.runtime.onInstalled.addListener(() => {
    chrome.contextMenus.create({
        id: "downloadImage",
        title: "Download Image",
        contexts: ["image"]
    });
    chrome.contextMenus.create({
        id: "recodeWeb",
        title: "Record Web",
        // contexts: ["image"]
    });
});

chrome.contextMenus.onClicked.addListener(async (info, tab) => {
    if(info.menuItemId === "recodeWeb"){
        console.log("----info----", info, tab)
        const {favIconUrl, title, url} = tab;
        const response = await fetch('https://jsz315.xyz/mps/bookmarks', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ favIconUrl, title, url }),
        });
        const result = await response.json();
        if (response.ok) {
            // document.getElementById('tagName').value = '';
            // fetchTags();
            showMsg("保存成功");
        } else {
            // alert(result.message);
            showMsg("保存失败");
            console.error('Fetch error:', result.message)
        }

    }
    if (info.menuItemId === "downloadImage" && info.srcUrl) {
        // chrome.runtime.sendMessage({ url: info.srcUrl });

        fetch(`https://jsz315.xyz/mps/download?url=${encodeURIComponent(info.srcUrl)}`)
            .then(response => {
                if (response.ok) {
                    // alert(1);
                    showMsg("下载保存成功");
                } else {
                    showMsg("使用扩展下载");
                    googleDownload(info.srcUrl);
                    throw new Error('Error fetching images');
                }
            })
            .catch(error => {
                console.error('Fetch error:', error)
                showMsg("使用浏览器下载");
                googleDownload(info.srcUrl);
            });
    }
});

function showMsg(message) {
    chrome.notifications.create({
        type: 'basic',
        iconUrl: 'images/icon-16.png', // 指定图标路径
        title: 'Download Status',
        message: message
    });
}

function googleDownload(url) {
    chrome.downloads.download({ url }, function (downloadId) {
        console.log("开始下载", url);
        // 监听下载状态变化
        chrome.downloads.onChanged.addListener(function (delta) {
            if (delta.id === downloadId && delta.state && delta.state.current === "complete") {
                console.log("完成下载");
                // 请求文件访问权限
                chrome.fileSystem.getWritableEntry(delta.id, function (entry) {
                    if (!entry) {
                        console.error("无法访问下载的文件");
                        return;
                    }

                    // 使用 File API 读取文件
                    entry.file(function (file) {
                        const reader = new FileReader();
                        reader.onload = function (e) {
                            const arrayBuffer = reader.result;
                            // 将 ArrayBuffer 转换为 Blob
                            const blob = new Blob([arrayBuffer], { type: 'image/jpeg' });
                            uploadImg(blob);
                        };
                        reader.readAsArrayBuffer(file);
                    });
                });
            }
        });
    });
}


function showNotification() {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        if (tabs && tabs.length > 0) {
            // tabs[0] 是当前活动标签页
            chrome.tabs.executeScript(tabs[0].id, { code: 'alert(1);' });
        }
    });
    // if (Notification.permission === 'granted') {
    //     new Notification('Download Successful', {
    //         body: 'Your image has been downloaded successfully.',
    //         // icon: '/path/to/icon.png' // 确保路径正确
    //     });
    // } else {
    //     Notification.requestPermission().then(permission => {
    //         if (permission === 'granted') {
    //             showNotification();
    //         }
    //     });
    // }
}

function test(str) {
    // console.log(str, "iii")
    // const code = `alert('${str}');`;
    // const executeScript = new Function(code);
    // executeScript();

    function executeDynamicScript(code) {
        const script = document.createElement('script');
        script.textContent = code;
        document.body.appendChild(script);
        document.body.removeChild(script);
    }

    // 示例用法
    const code = "alert('Hello, world!');";
    executeDynamicScript(code);
}


chrome.webNavigation.onDOMContentLoaded.addListener(async ({ tabId, url }) => {
    console.log("cur url", url);

    webs.forEach(i => {
        if (url.includes(i.name)) {
            chrome.scripting.executeScript({
                target: { tabId },
                files: ["script/" + i.name + ".js"],
            });
        }
    })



    if (url.includes("/twitter.com") || url.includes("/x.com")) {

        // chrome.scripting.executeScript({
        //     target: { tabId },
        //     func: test,
        //     args: ['ok']
        // });

        chrome.scripting.executeScript({
            target: { tabId },
            files: ["script.js"],
        });

        chrome.scripting.executeScript({
            target: { tabId },
            func: (webs) => {
                console.log("insert js script");
                localStorage.setItem("webs", JSON.stringify(webs))
            },
            args: [webs]
        });

        chrome.scripting.insertCSS({
            target: { tabId },
            files: ["style.css"],
        })
    }

    // function showTip(c) {
    //     start(c)
    // }

    // chrome.tabs.query({}, function (tabs) {
    //     tabs.forEach(function (tab) {
    //         const tabId = tab.id;
    //         if (tab.url.includes("twitsave.com")) {
    //             chrome.scripting.executeScript({
    //                 target: { tabId },
    //                 func: showTip,
    //                 args: ["red"],
    //             });
    //         }
    //     });
    // });
});

let temp = "9"
chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        // let options = {
        //     type: 'basic',
        //     title: 'Basic Notification',
        //     message: request,
        //     iconUrl: 'icon.png'
        // };

        console.log("request", request)
        console.log("sender", sender)
        console.log("sendResponse", sendResponse)
        // chrome.notifications.create("reminder", options, function (id) {
        //     console.log(id)
        // });

        if (request.action == "save") {
            temp = request.url;
        }
        else if (request.action == "read") {
            sendResponse({ url: temp })
        }
        else if (request.action == "img") {

            sendResponse(request.poster + " [img]")
        }

        function showTip(c) {
            start(c)
        }

        chrome.tabs.query({}, function (tabs) {
            tabs.forEach(function (tab) {
                const tabId = tab.id;
                if (tab.url.includes("twittervideodownloader.com")) {
                    // chrome.scripting.executeScript({
                    //     target: { tabId },
                    //     func: showTip,
                    //     args: [request],
                    // });
                    // sendResponse(temp)
                }
            });
        });
    }
);

chrome.runtime.onConnect.addListener(function (port) {
    console.log(port.name + " conn name");
    port.onMessage.addListener(function (msg) {
        console.log("get msg", msg)
        port.postMessage(msg.poster);
        downloadImg(msg.poster)
    });
});

function downloadImg(imageUrl) {
    fetch(imageUrl)
        .then(response => response.blob()) // 将响应转换为Blob对象
        .then(blob => {
            // 创建一个URL表示Blob对象
            // const imageUrl = URL.createObjectURL(blob);
            console.log("blob", blob)
            uploadImg(blob)
        }).catch(error => console.error(error));
}

async function uploadImg(blob) {

    const formData = new FormData();
    formData.append('file', blob);

    try {
        const response = await fetch('https://jsz315.xyz/mps/upload', {
            method: 'POST',
            body: formData,
        });

        if (response.ok) {
            console.log('File uploaded successfully');
            showMsg("保存成功")

        } else {
            showMsg("保存失败")
            throw new Error('Error uploading file');
        }
    } catch (error) {
        showMsg("上传失败")
        console.error(error);
    }
}